﻿using DG.Tweening;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;

public class ZoneUI : MonoBehaviour, IZoneListen
{

    public GameObject toggleDrawBorder = null;
    public bool isToggleBorder = false;

    public GameObject toggleDrawBlock = null;
    public bool isToggleBlock = false;

    public GameObject buttonSave = null;
    public GameObject _Content = null;

    public ToggleGroupCtrl toggleGroupCtrl = null;

    public nUnitType _nLayerType = nUnitType.Null;

    public static ZoneUI Instance;

    private void Awake()
    {
        Instance = this;
    }

    // Use this for initialization
    void Start ()
    {

        {
            isToggleBorder = ZoneManager.isDrawBorder;

            Toggle toggle = toggleDrawBorder.GetComponent<Toggle>();
            toggle.isOn = isToggleBorder;

            toggle.onValueChanged.AddListener((value) =>
            {
                OnValueChangedDraw(value);
            });

        }

        {
            isToggleBlock = ZoneManager.isDrawBlock;

            Toggle toggle = toggleDrawBlock.GetComponent<Toggle>();
            toggle.isOn = isToggleBlock;

            toggle.onValueChanged.AddListener((value) =>
            {
                OnValueChangedBlock(value);
            });

        }

        {
            Button button = buttonSave.GetComponent<Button>();

            button.onClick.AddListener(() =>
            {
                OnSave();
            });

        }

        ((IToggleGroupCtrl)toggleGroupCtrl).AddListen(OnToggleGroupCtrlChanged);
    }

    public float alpha_hint = 1;

    // Update is called once per frame
    void Update ()
    {
        Color c = textHint.color;

        if (c.a > 0)
        {
            c.a -= Time.deltaTime;
            textHint.color = c;
        }
	}

    public void OnValueChangedDraw(bool flag)
    {
        Debug.Log(flag);

        ZoneManager.EnableGizmos(flag);
    }

    public void OnValueChangedBlock(bool flag)
    {
        Debug.Log(flag);

        ZoneManager.EnableBlock(flag);
    }

    void OnToggleGroupCtrlChanged(string togglename, bool flag)
    {
        Debug.Log("OnToggleGroupCtrlChanged " + togglename + " " + flag);

        for (int m = 0;m < toggleGroupCtrl.toggles.Length; ++m)
        {
            bool isflag = toggleGroupCtrl.toggles[m].isOn;

            switch(m)
            {
                case 0:
                    if (isflag)
                    {
                        _nLayerType = nUnitType.Building;

                        LoadRes(nUnitType.Building);
                        ZoneManager.LO = nLayerOrder.Building;
                    }

                    break;
                case 1:

                    if (isflag)
                    {
                        _nLayerType = nUnitType.Wall;

                        LoadRes(nUnitType.Wall);
                        ZoneManager.LO = nLayerOrder.Wall;
                    }
                    break;
                case 2:

                    if (isflag)
                    {
                        _nLayerType = nUnitType.Decoration;

                        LoadRes(nUnitType.Decoration);
                        ZoneManager.LO = nLayerOrder.Decos;
                    }
                    break;
                case 3:

                    if (isflag)
                    {
                        _nLayerType = nUnitType.Triggers;

                        LoadRes(nUnitType.Triggers);
                        ZoneManager.LO = nLayerOrder.Triggers;
                    }
                    break;
                case 4:

                    if (isflag)
                    {
                        _nLayerType = nUnitType.Foundation;

                        LoadRes(_nLayerType);
                        ZoneManager.LO = nLayerOrder.Foundation;
                    }
                    break;
                case 5:

                    if (isflag)
                    {
                        _nLayerType = nUnitType.Role;

                        LoadRes(_nLayerType);
                        ZoneManager.LO = nLayerOrder.Decos;
                    }
                    break;
                    //default:
                    //    {
                    //        _nLayerType = nLayerType.Null;

                    //        LoadRes(nLayerType.Null);
                    //        ZoneManager.LO = LayerOrder.Null;
                    //    }
                    //    break;
            }
        }

        ZoneManager.Instance.Clear();
    }

    public void OnSave()
    {
        if (ZoneManager.CurIndex == -1)
            return;

        ZoneManager.Instance.SaveRelationZone();

        ZoneManager.Instance.SaveZone();
    }

    #region 装饰
    public Button _ButtonTem;

    void LoadRes(nUnitType type)
    {
        foreach (Button button in _Content.GetComponentsInChildren<Button>())
        {
            Destroy(button.gameObject);
        }

        if (type == nUnitType.Null)
            return;

        nUnitData[] files =  ZoneManager.Instance._ZoneMediaManager.GetAllRes(type);
        if (files == null)
            return;

        for (int i = 0; i < files.Length; ++i)
        {
            Button b = GameObject.Instantiate(_ButtonTem);

            Image img = b.GetComponent<Image>();

            img.sprite = AssetManager.Instance.GetResourceObject<Sprite>(files[i]._res_name);

            b.transform.parent = _Content.transform;

            Text text = b.GetComponentInChildren<Text>();

            text.text = Path.GetFileNameWithoutExtension(files[i]._unit_name);

            b.gameObject.name = files[i].id.ToString();

            AddDownEvent(b);

        }

        RectTransform rectTransform = _Content.GetComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(0, 100 * files.Length);
    }

    void AddDownEvent(Button button)
    {
        EventTrigger trigger = button.GetComponent<EventTrigger>();
        if (trigger == null)
            trigger = button.gameObject.AddComponent<EventTrigger>();

        // 实例化delegates
        trigger.triggers = new List<EventTrigger.Entry>();

        {
            // 定义需要绑定的事件类型。并设置回调函数
            EventTrigger.Entry entry = new EventTrigger.Entry();
            // 设置 事件类型
            entry.eventID = EventTriggerType.PointerDown;
            // 设置回调函数
            entry.callback = new EventTrigger.TriggerEvent();
            UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(TouchDown);
            entry.callback.AddListener(callback);
            // 添加事件触发记录到GameObject的事件触发组件
            trigger.triggers.Add(entry);

        }
        {
            // 定义需要绑定的事件类型。并设置回调函数
            EventTrigger.Entry entry = new EventTrigger.Entry();
            // 设置 事件类型
            entry.eventID = EventTriggerType.PointerUp;
            // 设置回调函数
            entry.callback = new EventTrigger.TriggerEvent();
            UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(TouchUp);
            entry.callback.AddListener(callback);
            // 添加事件触发记录到GameObject的事件触发组件
            trigger.triggers.Add(entry);
        }
        {
            // 定义需要绑定的事件类型。并设置回调函数
            EventTrigger.Entry entry = new EventTrigger.Entry();
            // 设置 事件类型
            entry.eventID = EventTriggerType.Drag;
            // 设置回调函数
            entry.callback = new EventTrigger.TriggerEvent();
            UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(TouchDrag);
            entry.callback.AddListener(callback);
            // 添加事件触发记录到GameObject的事件触发组件
            trigger.triggers.Add(entry);
        }
    }

    public static UnitObject _clickOB = null;

    public void TouchDown(BaseEventData arg0)
    {
        Debug.Log("TouchDown");

        if (ZoneManager.CurIndex == -1)
            return;

        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        pos.z = 0;

        if (_nLayerType == nUnitType.Decoration ||
            _nLayerType == nUnitType.Role)
        {
            nUnitData ud =  ZoneManager.Instance._ZoneMediaManager.GetDataByID(int.Parse(arg0.selectedObject.name));

            _clickOB = ZoneManager.Instance._ZoneFactory.AddDecoObject(ud);

            ZoneManager.PushZoneDeco(_clickOB);

            ZoneManager.Instance.VirualObject(_clickOB);

            return;

        }

        if (_nLayerType == nUnitType.Wall)
        {
            nUnitData ud =  ZoneManager.Instance._ZoneMediaManager.GetDataByID(int.Parse(arg0.selectedObject.name));

            _clickOB = ZoneManager.Instance._ZoneFactory.AddFoundationObject(ud);

            ZoneManager.PushZoneWall(_clickOB);

            ZoneManager.Instance.VirualObject(_clickOB);

            return;

        }

        if (_nLayerType == nUnitType.Foundation)
        {
            nUnitData ud =  ZoneManager.Instance._ZoneMediaManager.GetDataByID(int.Parse(arg0.selectedObject.name));

            _clickOB = ZoneManager.Instance._ZoneFactory.AddFoundationObject(ud);

            ZoneManager.PushZoneFoundation(_clickOB);

            ZoneManager.Instance.VirualObject(_clickOB);

            return;

        }

        if (_nLayerType == nUnitType.Building)
        {

            ZoneManager.Instance.floor = arg0.selectedObject.name;

            return;
        }

        ZoneManager.Instance.floor = string.Empty;

        _clickOB = null;
    }

    public void TouchUp(BaseEventData arg0)
    {
        Debug.Log("TouchUp");

        if (ZoneManager.CurIndex == -1)
            return;

        _IC.OnPointerUp((PointerEventData)arg0);

        //_clickOB = null;
    }

    public void TouchDrag(BaseEventData arg0)
    {
        if (ZoneManager.CurIndex == -1)
            return;

        _IC.OnDrag((PointerEventData)arg0);
    }

    public Text textHint;

    public InputManager _IC;
    #endregion

    #region DropDown
    public Dropdown Drd_IPList;

    void InitDropDown()
    {
        for (int i = 0; i < ZoneManager.Instance._ZoneFile.GetZoneCount(); ++i)
        {
            Dropdown.OptionData op1 = new Dropdown.OptionData();
            op1.text = ZoneManager.Instance._ZoneFile.GetZonecell(i).zonefilename;
            Drd_IPList.options.Add(op1);
        }

        Drd_IPList.onValueChanged.AddListener(ClickDropdown);

        isDone = true;
    }

    private void ClickDropdown(int index)
    {
        if (!IsDone())
            return;

        Debug.Log(Drd_IPList.options[index].text);

        ZoneManager.Instance.LoadZone(index);
    }

    bool isDone = false;

    public void LoadDone()
    {
        OnToggleGroupCtrlChanged(string.Empty, true);

        InitDropDown();
    }

    public bool IsDone()
    {
        return isDone;
    }

    public void Go()
    {
        if (ZoneManager.Instance._ZoneFile.GetZoneCount() >= 1)
        {
            Drd_IPList.value = 1;

            ClickDropdown(1);
        }
    }

    public void UnloadDone()
    {
        throw new NotImplementedException();
    }
    #endregion

}
